<template>
  <Treeselect
    v-bind="$attrs"
    :value="value"
    :options="options"
    no-results-text="暂无数据"
    :normalizer="normalizer"
    no-options-text="暂无数据"
    :default-expand-level="2"
    placeholder="请选择"
    style="width: 100%;"
    @input="input"
    @open="open"
  />
</template>

<script>
  import request from '@/utils/request'
  import Treeselect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  // utils
  import { treeToList, listToTree } from '@/utils'
  export default {
    name: 'JtTree',
    components: {
      Treeselect
    },
    model: {
      prop: 'value',
      event: 'input'
    },
    props: {
      value: Number,
      url: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        options: [],
        normalizer(node) {
          if (node.children == null || node.children === 'null') {
            delete node.children
          }
          return {
            id: node.id,
            label: node.name,
            children: node.children
          }
        }
      }
    },
    created() {
      this.remoteMethod()
    },
    methods: {
      // 获取远程数据并赋值
      remoteMethod() {
        request({
          url: this.url,
          method: 'GET',
          params: {
            page: 0,
            size: 999999,
            sort: 'id,desc'
          }
        }).then(res => {
          if (res) {
            const tree = []
            const arr = treeToList(res.content ? res.content : res, 'children').filter(item => item.status === 1)
            console.log("???",arr)
            listToTree(arr, tree, 0)
            this.options = [{ id: 0, name: '根目录' }].concat(tree)
          }
        }).catch(e => {
          this.options = []
          this.$notify.error({
            title: '数据请求失败',
            duration: 5000
          })
        })
      },
      input(event) {
        this.$emit('input', event)
      },
      open() {
        this.remoteMethod()
      }
    }
  }
</script>

<style>
  .vue-treeselect {
    height: 32px;
    line-height: 32px;
  }

  .vue-treeselect__control {
    height: 32px;
    line-height: 32px;
  }

  .vue-treeselect__placeholder,
  .vue-treeselect__single-value {
    line-height: 32px;
  }
</style>
